/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:42
 */

package com.lenovo.mso2o.ui.adapter;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.lenovo.framework.FApplication;
import com.lenovo.framework.base.BaseDialogFragment;
import com.lenovo.framework.base.FBaseActivity;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.conf.FConstants;
import com.lenovo.framework.entity.Res;
import com.lenovo.framework.rest.NetworkObserver;
import com.lenovo.framework.rx.RxBus;
import com.lenovo.framework.service.LocationService;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.maputil.MapDistance;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.BizErrorCode;
import com.lenovo.mso2o.conf.ErrorCode;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.conf.OrderAction;
import com.lenovo.mso2o.conf.OrderLevel;
import com.lenovo.mso2o.entity.Order;
import com.lenovo.mso2o.entity.OrderShortcut;
import com.lenovo.mso2o.entity.OrderStatus;
import com.lenovo.mso2o.entity.OrderUpdatingRequest;
import com.lenovo.mso2o.entity.g.AutoSignOrder;
import com.lenovo.mso2o.entity.g.AutoSignOrderDao;
import com.lenovo.mso2o.entity.g.Notification;
import com.lenovo.mso2o.entity.g.NotificationDao;
import com.lenovo.mso2o.rest.OrderAPI;
import com.lenovo.mso2o.rest.ServiceGenerator;
import com.lenovo.mso2o.ui.MainActivity;
import com.lenovo.mso2o.ui.WebActivity;
import com.lenovo.mso2o.ui.fragment.OrderGrabListFragment;
import com.lenovo.mso2o.ui.fragment.OrderListFragment;
import com.lenovo.mso2o.ui.fragment.POISearchDialogFragment;
import com.lenovo.mso2o.ui.fragment.SignFailureChoiceFragment;
import com.lenovo.mso2o.util.ActionCallbacks;
import com.lenovo.mso2o.util.CommonUtil;
import com.lenovo.mso2o.util.SendNotification;
import com.lenovo.mso2o.util.Utils;
import com.trello.rxlifecycle.components.support.RxFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import de.greenrobot.dao.query.QueryBuilder;
import rx.Scheduler;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by hippo on 6/4/15.
 */

public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.OrderViewHolder> {
    public static final int STEP_REQUEST = 0x32;
    ArrayList<Order> orderList = new ArrayList<>();
    ArrayList<Order> orderShadowList;
    OnOrderSelectedListener listener;
    //private static AutoSignOrderDao autoSignOrderDao;
    private static SimpleDateFormat formater;
    private static SimpleDateFormat hourMinFormater;
    private int type;//Fragment 类型匹配不同状态
    private static Scheduler.Worker worker;
    private static int DATE_LEN = 2;
    private OrderAPI orderAPI;
    private static Subscription _subscription;
    private OrderListFragment fragment;


    public OrderAdapter(int type, Scheduler.Worker worker, OrderListFragment fragment) {
        this.type = type;
        this.worker = worker;
        this.fragment = fragment;
        formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MapDistance md = MapDistance.getInstance();
        orderAPI = ServiceGenerator.createService(OrderAPI.class);
    }


    public void setLocation(Location location) {
        notifyDataSetChanged();
    }

    public void setLatLng(com.baidu.mapapi.model.LatLng location) {
        notifyDataSetChanged();
    }


    public void setOnOrderSelectedListener(OnOrderSelectedListener listener) {
        this.listener = listener;
    }

    @Override
    public OrderViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View view = inflater.inflate(R.layout.order_item, viewGroup, false);
        return new OrderViewHolder(view);
    }

    @Override
    public void onBindViewHolder(OrderViewHolder holder, int position, List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
    }

    @Override
    public void onBindViewHolder(final OrderViewHolder holder, final int i) {
        final Order order = orderList.get(i);
        OrderAdapter.onBindOrder(holder, order, type, worker, orderAPI, fragment, this);
    }

    public static void onBindOrder(final com.lenovo.mso2o.ui.adapter.OrderViewHolder holder, final Order order, int type, final Scheduler.Worker worker, final OrderAPI orderAPI, final RxFragment fragment) {
        onBindOrder(holder, order, type, worker, orderAPI, fragment, null);
    }

    /*优先级显示规则：低+无时间 不显示
    低+2 显示优先2小时
    低+4 显示优先4小时
    低+8 显示优先8小时

    中+无时间 显示优先
    中+2 显示优先2小时
    中+4 显示优先4小时
    中+8 显示优先8小时

    高+无时间 显示优先
    高+2 显示优先2小时
    高+4 显示优先4小时
    高+8 显示优先8小时*/
    private static void showPriority(ImageView priorityView, String heightLow, String twoFourHeight) {
        if (OrderLevel.ORLDER_LEVEL_NORMAL.getLevel().equals(heightLow) || OrderLevel.ORLDER_LEVEL_HIGH.getLevel().equals(heightLow)) {
            if (OrderLevel.TWO_HOUR.getLevel().equals(twoFourHeight)) {
                priorityView.setImageResource(R.drawable.priority2);
            } else if (OrderLevel.FOUR_HOUR.getLevel().equals(twoFourHeight)) {
                priorityView.setImageResource(R.drawable.priority4);
            } else {
                priorityView.setImageResource(R.drawable.priority);
            }
        } else {
            priorityView.setVisibility(View.GONE);
        }
    }

    public static void onBindOrder(final com.lenovo.mso2o.ui.adapter.OrderViewHolder holder, final Order order, int type, final Scheduler.Worker worker, final OrderAPI orderAPI, final RxFragment fragment, final OrderAdapter adapter) {

        String title = order.getTitle() == null ? "" : replaceNull(order.getTitle());
        if (title.length() > 20)
            title = title.substring(0, 20) + "...";
        holder.topTV1.setText(title);

        switch (type) {
            case MSConstants.FragmentType.FRAGMENT_GRABORDERS://抢单
                //第一行
                holder.topTV1.setVisibility(View.VISIBLE);
                holder.topTV2.setVisibility(View.VISIBLE);
                holder.topTV3.setVisibility(View.VISIBLE);
                //holder.hour_topTV.setVisibility(View.GONE);
                //第二行
                holder.layoutContentTV1.setVisibility(View.VISIBLE);
                holder.layoutContentTV2.setVisibility(View.VISIBLE);
                holder.contentDistanceTV.setVisibility(View.VISIBLE);
                holder.layoutContentTV3.setVisibility(View.VISIBLE);
                holder.contentRelative.setVisibility(View.VISIBLE);
                //第三行
                holder.bottomLinear.setVisibility(View.VISIBLE);

                //新加入布局
                holder.layout_worksheet_left.setVisibility(View.GONE);
                holder.layout_back_layout.setVisibility(View.GONE);
                holder.layout_grab_order.setVisibility(View.VISIBLE);
                holder.layout_grab_time.setVisibility(View.VISIBLE);

                //holder.hour_topTV.setText(order.getRespondLevel());

                final Date[] dates = order.getTimers();
                long curr = System.currentTimeMillis();
                if (dates != null && dates.length > 0) {
                    Date last = null;
                    for (Date date : dates) {
                        if (curr < date.getTime()) {
                            last = date;
                            break;
                        }
                    }
                    if (last == null) {
                        //说明时间值超过，删掉这个item吧
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                if (adapter != null) {
                                    adapter.getOrderList().remove(order);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        });
                    } else {
                        //刷新工单列表
                        if (last.getTime() - System.currentTimeMillis() < 1000) {
                            RxBus rxBus = FApplication.getRxBus();
                            rxBus.send(OrderGrabListFragment.REFRESH_LIST);
                        }
                        Date remain = new Date(last.getTime() - System.currentTimeMillis());
                        hourMinFormater = new SimpleDateFormat("mm:ss");
                        if (remain.getTime() >= 0) {
                            holder.grab_timeTV.setText("倒计时:" + hourMinFormater.format(remain));
                        }
                    }
                    //倒计时 和服务器给的值作比较，若当前时间小于第一个时间，则和第一个时间点相减
                    /*StringBuilder builder = new StringBuilder();
                    TimeUtils.formatDuration(last.getTime() - System.currentTimeMillis(), builder);*/
                }
                holder.topTV2.setText("工单编号:" + order.getTicketid() + "");
                showPriority(holder.topTV3, order.getPriority(), order.getRespondLevel());
                //超时提醒
                //DLog.i("超时提醒；" , order.getStatus().toString());
                if (order.getStatus() != null && order.getStatus().getValue() != null
                        && order.getStatus().getValue().length == 2
                        && order.getStatus().getValue()[1] != null) {
                    final String overtime = order.getStatus().getCode() + ": " + formater.format((order.getStatus().getValue())[1]);
                    holder.contentTV1.setText(overtime);
                } else {
                    holder.contentTV1.setText("预约超时时间：暂无");
                }
                //获取当前时间
                holder.contentTV2.setText("上门地址:" + order.getCaddress());
                holder.contentTV3.setText("项目名称:" + replaceNull(order.getProject()));

                holder.contentRelative.setBackgroundResource(R.drawable.bg_orderlistitem_giveofforder_receiveorder);
                setImgViewParams(holder.contentRelative, 0.5);
                Drawable grab_draw = ContextManager.context().getResources().getDrawable(R.drawable.icon_orderlistitem_confirm);
                holder.grab_orderTV.setCompoundDrawables(grab_draw, null, null, null);
                holder.grab_orderTV.setText(ContextManager.context().getString(R.string.graborder));
                //// TODO: 2015/12/23
                final AlphaAnimation animation = new AlphaAnimation(1, 0);
                animation.setDuration(500);//设置动画持续时间
                animation.setRepeatCount(10);
                holder.grab_orderTV.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ActionCallbacks.grabOrder(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        //holder.grab_orderPb.setVisibility(View.VISIBLE);
                                        ((FBaseActivity) (fragment.getActivity())).processPreview("抢单中", null, false);
                                        //holder.grab_orderTV.setVisibility(View.GONE);
                                    }
                                },
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        ((FBaseActivity) (fragment.getActivity())).processDismiss();
                                        String action = "/tickets/" + order.getTicketid() + "/" + OrderAction.GRAB.getValue();
                                        ActionCallbacks.uploadInfoAsync(fragment.getActivity(), action);
                                        //holder.grab_orderPb.setVisibility(View.GONE);
                                        //holder.grab_orderTV.setVisibility(View.VISIBLE);
                                    }
                                },
                                order, fragment, orderAPI, worker
                        );
                    }
                });
                if (order.getcTime() != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String dateString = sdf.format(order.getcTime());
                    holder.bottom1.setText(dateString + "");
                } else {
                    holder.bottom1.setText("");
                }
                if (order.getShortcut() != null)
                    holder.bottom2.setText(order.getShortcut().getName() + "");
                break;
            case MSConstants.FragmentType.FRAGMENT_RECEIVEORDERS://接单池
                // 第一行
                holder.topTV1.setVisibility(View.VISIBLE);
                holder.topTV2.setVisibility(View.VISIBLE);
                holder.topTV3.setVisibility(View.VISIBLE);
                //holder.hour_topTV.setVisibility(View.GONE);
                //第二行
                holder.layoutContentTV1.setVisibility(View.VISIBLE);
                holder.layoutContentTV2.setVisibility(View.VISIBLE);
                holder.contentDistanceTV.setVisibility(View.VISIBLE);
                holder.layoutContentTV3.setVisibility(View.VISIBLE);
                holder.contentRelative.setVisibility(View.VISIBLE);
                //第三行
                holder.bottomLinear.setVisibility(View.VISIBLE);

                //新加入布局
                holder.layout_worksheet_left.setVisibility(View.GONE);
                holder.layout_back_layout.setVisibility(View.VISIBLE);
                holder.layout_grab_order.setVisibility(View.GONE);
                holder.layout_grab_time.setVisibility(View.GONE);

                //逻辑操作
                //holder.hour_topTV.setText(order.getRespondLevel());
                holder.back_orderTV.setText("  退单");
                holder.make_orderTV.setText("  接单");

                holder.topTV2.setText(replaceNull("工单编号:" + order.getTicketid()));
                showPriority(holder.topTV3, order.getPriority(), order.getRespondLevel());
                if (order.getStatus() != null && order.getStatus().getValue() != null
                        && order.getStatus().getValue().length == 2
                        && order.getStatus().getValue()[1] != null
                        ) {
                    final String overtime1 = order.getStatus().getCode() + ": " + formater.format((order.getStatus().getValue())[1]);
                    holder.contentTV1.setText(overtime1);
                } else {
                    holder.contentTV1.setText("预约超时时间：暂无");
                }
                holder.contentTV2.setText("上门地址:" + order.getCaddress());
                holder.contentTV3.setText("项目名称:" + replaceNull(order.getProject()));
                holder.contentRelative.setBackgroundResource(R.drawable.bg_orderlistitem_giveofforder_receiveorder);
                setImgViewParams(holder.contentRelative, 0.5);
                holder.contentBtnTV.setText(R.string.receiveorder);
                //layout_back_cancle
                //holder.back_orderTV.setOnClickListener(new View.OnClickListener() {
                holder.layout_back_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ContextManager.context(), WebActivity.class);
                        intent.putExtra(WebActivity.ORDER, order);
                        intent.putExtra(FConstants.X5WEBVIEW_INITIAL_URL, String.format(MSConstants.APIConstants.ORDER_BACK, order.getTicketid()));
                        DLog.d("order detail", String.format(MSConstants.APIConstants.ORDER_BACK, order.getTicketid()));
                        fragment.startActivityForResult(intent, MSConstants.FragmentType.FRAGMENT_RECEIVEORDERS);
                    }
                });
                //holder.make_orderTV.setOnClickListener(new View.OnClickListener() {
                holder.layout_back_receive.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //进入详情页面
                        /*holder.make_orderPb.setVisibility(View.VISIBLE);
                        holder.make_orderTV.setVisibility(View.GONE);*/
                        ((FBaseActivity) (fragment.getActivity())).processPreview("接单中", null, false);
                        if (_subscription == null || _subscription.isUnsubscribed())
                            _subscription = orderAPI.updateOrderAppoint(order.getTicketid(), OrderAction.CONFIRM.getValue(), new OrderUpdatingRequest())
                                    // Started in onStart(), running until in onStop()
                                    .compose(fragment.<Res<String>>bindToLifecycle())
                                    .subscribeOn(Schedulers.io())
                                    .doOnTerminate(new Action0() {
                                        @Override
                                        public void call() {
                                            _subscription = null;
                                        }
                                    })
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .unsubscribeOn(Schedulers.io())
                                    .subscribe(new NetworkObserver<Res<String>>() {
                                        @Override
                                        public void onSuccess(Res<String> result) {
                                            ((FBaseActivity) (fragment.getActivity())).processDismiss();
                                            /*holder.make_orderPb.setVisibility(View.GONE);
                                            holder.make_orderTV.setVisibility(View.VISIBLE);*/
                                            //接单成功 上传信息
                                            if (result.getEcode() != 0) {
                                                ErrorCode bizErrorCode = BizErrorCode.errorMap.get(result.getEcode());
                                                if (bizErrorCode != null) {
                                                    onFailure(bizErrorCode.getReason());
                                                } else {
                                                    if (result.getReason() != null && !TextUtils.isEmpty(result.getReason()))
                                                        onFailure(result.getReason());
                                                    else
                                                        onFailure(fragment.getString(R.string.unknown_error));
                                                }
                                                return;
                                            }
                                            String action = "/tickets/" + order.getTicketid() + "/" + OrderAction.CONFIRM.getValue();
                                            ActionCallbacks.uploadInfoAsync(fragment.getActivity(), action);
                                            //TODO
                                            gotoAppointPage(fragment, order, result.getResult(), MSConstants.FragmentType.FRAGMENT_RECEIVEORDERS);
                                        }

                                        @Override
                                        public void onFailure(String tip) {
                                            ((FBaseActivity) (fragment.getActivity())).processDismiss();
                                            Toast.makeText(ContextManager.context(), tip, Toast.LENGTH_SHORT).show();
                                            /*holder.make_orderPb.setVisibility(View.GONE);
                                            holder.make_orderTV.setVisibility(View.VISIBLE);*/
                                        }
                                    });
                    }
                });
                break;
            case MSConstants.FragmentType.FRAGMENT_ACTIVORDERS://活动工单
                /*
                1，在响应SLA预警时间时仍未做过预约的工单会收到APP消息提醒：“响应预警：
                编号为:EV-10132-12000-20160426-0002工单在服务实施环节，需要您及时处理。”
                2，在响应SLA超时时间时仍未做过预约的工单会收到APP消息提醒：“响应超时：
                编号为:EV-10132-12000-20160426-0002工单在服务实施环节，需要您及时处理。”
                3，在“消息”列表中会有相应的消息记录。
                4，多条响应预警的APP消息在手机消息中只显示最新的1条；多条响应超时的APP消息在手机消息中只显示最新的1条。
                5，不要发生短信消息。
                6，工单只要预约过，之后都不会受到这些APP消息提醒（即便“下次再约”后工单处于待预约状态）。*/

                if (order.getDescription() != null && order.getDescription().length == 2) {
                    holder.bottom1.setText("已" + order.getDescription()[0]);
                    holder.bottom2.setText("待" + order.getDescription()[1]);
                }

                //在这个页面做 自动签到
                //定时器 每3秒 更新一次 得到当前位置的经纬度 和item中的经纬度作比较 若在1000m以内 就发一个通知 然后自动弹窗
                String overtime2 = null;
                if (order.getStatus() != null && order.getStatus().getValue() != null
                        && order.getStatus().getValue().length > 1
                        && order.getStatus().getValue()[1] != null) {
                    overtime2 = order.getStatus().getCode() + ": " + formater.format((order.getStatus().getValue())[1]);
                    // 显示超时时间
                    showOverTime(order, fragment.getActivity(), holder.contentRelative, holder.contentTV1, order.getStatus().getValue(), order.getStatus().getCode(), fragment.getString(R.string.no_over_time), holder.iconTimeGray, holder.iconNotOver, holder.iconOverTime);
                    // holder.contentTV1.setText(overtime2);
                    showPriority(holder.topTV3, order.getPriority(), order.getRespondLevel());
                } else {
                    holder.topTV3.setVisibility(View.GONE);
                    if (order.getStatus().getValue()[1] == null && order.getStatus().getCode() != null) {
                        holder.contentTV1.setText(order.getStatus().getCode() + ":" + "暂无");
                        holder.contentTV1.setTextColor(fragment.getResources().getColor(R.color.color_gray_over_time));
                        holder.iconNotOver.setVisibility(View.GONE);
                        holder.iconOverTime.setVisibility(View.GONE);
                        holder.iconTimeGray.setImageResource(R.drawable.icon_orderlistitem_giveorder_time);
                    }
                }
                OrderStatus status = order.getStatus();
                if (status != null && status.getValue() != null && status.getValue()[0] != null && status.getValue().length == 2) {
                    if (status.getValue()[0].getTime() - System.currentTimeMillis() > 0) {
                        final String finalOvertime = overtime2;
                        worker.schedule(new Action0() {
                            @Override
                            public void call() {
                                //TODO 闪烁
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        holder.contentTV1.setText(finalOvertime == null ? "" : finalOvertime);
                                    }
                                });
                                //holder.contentTV1.setText(order.getStatus() + "");
                            }
                        }, status.getValue()[0].getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
                    } else {
                        if (status.getValue() != null && status.getValue().length == 2 && status.getValue()[1] != null) {
                            final String finalOvertime = overtime2;
                            worker.schedule(new Action0() {
                                @Override
                                public void call() {
                                    //TODO 闪烁
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            holder.contentTV1.setText(finalOvertime == null ? "" : finalOvertime);
                                        }
                                    });
                                    //holder.contentTV1.setText(replaceNull(order.getStatus() + ""));
                                }
                            }, System.currentTimeMillis() - status.getValue()[1].getTime() > 0
                                    ? System.currentTimeMillis() - status.getValue()[1].getTime() : 0, TimeUnit.MILLISECONDS);
                        }
                    }
                }
                //第一行
                holder.topTV1.setVisibility(View.VISIBLE);
                holder.topTV2.setVisibility(View.VISIBLE);
                holder.topTV3.setVisibility(View.VISIBLE);
                //holder.hour_topTV.setVisibility(View.GONE);
                //第二行
                holder.layoutContentTV1.setVisibility(View.VISIBLE);
                holder.layoutContentTV2.setVisibility(View.VISIBLE);
                holder.contentDistanceTV.setVisibility(View.VISIBLE);
                holder.layoutContentTV3.setVisibility(View.VISIBLE);
                holder.contentRelative.setVisibility(View.VISIBLE);
                //第三行
                holder.bottomLinear.setVisibility(View.VISIBLE);

                //新加入布局
                holder.layout_worksheet_left.setVisibility(View.VISIBLE);
                holder.layout_back_layout.setVisibility(View.GONE);
                holder.layout_grab_order.setVisibility(View.GONE);
                holder.layout_grab_time.setVisibility(View.GONE);

                //赋值操作
                //holder.hour_topTV.setText(order.getRespondLevel());
                holder.topTV2.setText("工单编号:" + replaceNull(order.getTicketid()));

                final OrderShortcut shortcut = order.getShortcut();

                if (shortcut != null) {
                    String operationName = shortcut.getName();
                    holder.contentBtnTV.setText(operationName + "");
                    if (fragment.getString(R.string.appoint).equals(operationName)) {
                        holder.contentBtnIV.setBackgroundResource(R.drawable.icon_order_short_cut_appointment);
                    } else if (fragment.getString(R.string.reached).equals(operationName)) {
                        holder.contentBtnIV.setBackgroundResource(R.drawable.icon_order_sign_short_cut);
                    } else if (fragment.getString(R.string.done).equals(operationName)) {
                        holder.contentBtnIV.setBackgroundResource(R.drawable.icon_order_done_short_cut);
                    } else if (fragment.getString(R.string.evaluate).equals(operationName)) {
                        holder.contentBtnIV.setBackgroundResource(R.drawable.icon_order_evaluate_short_cut);
                    }
                    Glide.with(fragment.getContext()).load(shortcut.getIcon()).listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            DLog.p(e);
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            holder.contentBtnTV.setCompoundDrawables(resource, null, null, null);
                            holder.contentBtnTV.setCompoundDrawablePadding(3);
                            return false;
                        }
                    }).into(new ImageView(fragment.getContext()));
                    //holder.contentBtnTV.setOnClickListener(new View.OnClickListener() {
                    holder.layout_confirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (fragment.getActivity().getString(R.string.reached).equals(shortcut.getName())) {
                                final LatLng[] latLng = {LocationService.getRealTimeLatLng()};
                                final Runnable signRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        double distanceBetween = DistanceUtil.getDistance(latLng[0], new LatLng(order.getLatitude(), order.getLongitude()));
                                        if (distanceBetween <= MSConstants.RADIS_MIN_SIGN) {
                                            OrderUpdatingRequest signRequest = new OrderUpdatingRequest();
                                            //由于自动签到和手动签到要作区分，所以新给的参数{"fields":{"signtype":0}}表示自动签到
                                            Map<String, Integer> mMap = new HashMap<>();
                                            mMap.put("signtype", 0);
                                            signRequest.setFields(mMap);
                                            ServiceGenerator.createService(OrderAPI.class).updateOrder(order.getTicketid(), OrderAction.SIGININ.getValue(), signRequest)
                                                    // Started in onStart(), running until in onStop()
                                                    //.compose(fragment.<Res>bindUntilEvent(FragmentEvent.DESTROY))
                                                    .subscribeOn(Schedulers.io())
                                                    .observeOn(AndroidSchedulers.mainThread())
                                                    .unsubscribeOn(Schedulers.io())
                                                    .doOnTerminate(new Action0() {
                                                        @Override
                                                        public void call() {
                                                        }
                                                    })
                                                    .subscribe(new NetworkObserver<Res>() {
                                                        @Override
                                                        public void onSuccess(Res result) {
                                                            //webActivity.processDismiss();
                                                            if (result.getEcode() != 0) {
                                                                Toast.makeText(fragment.getActivity(), "签到失败，请手动签到，上传附件", Toast.LENGTH_SHORT).show();
                                                            } else {
                                                                Toast.makeText(fragment.getActivity(), "签到成功", Toast.LENGTH_SHORT).show();
                                                                RxBus rxBus = FApplication.getRxBus();
                                                                rxBus.send(OrderListFragment.REFRESH_ACTIVE_LSIT);
                                                            }
                                                        }

                                                        @Override
                                                        public void onFailure(String tip) {
                                                            //webActivity.processDismiss();
                                                            Toast.makeText(fragment.getActivity(), "签到失败，请手动签到，上传附件", Toast.LENGTH_SHORT).show();
                                                            DialogFragment search = new SignFailureChoiceFragment();
                                                            Bundle b = new Bundle();
                                                            if (order != null && order.getTicketid() != null)
                                                                b.putString(fragment.getActivity().getString(R.string.ticketid), order.getTicketid());
                                                            b.putString(fragment.getActivity().getString(R.string.location_invalid_info), "签到失败, 请拍照到场");
                                                            b.putBoolean(BaseDialogFragment.DISMISSABLE, true);
                                                            search.setArguments(b);
                                                            search.show(fragment.getActivity().getSupportFragmentManager(), POISearchDialogFragment.TAG);
                                                        }
                                                    });
                                        } else {//距离相距太远要上传照片
                                            //Toast.makeText(fragment.getActivity(), "距离太远，请手动签到，上传照片", Toast.LENGTH_SHORT).show();
                                            DialogFragment search = new SignFailureChoiceFragment();
                                            Bundle b = new Bundle();
                                            if (order != null && order.getTicketid() != null)
                                                b.putString(fragment.getActivity().getString(R.string.ticketid), order.getTicketid());
                                            b.putString(fragment.getActivity().getString(R.string.location_invalid_info), fragment.getString(R.string.gps_say_you_are_too_long));
                                            b.putBoolean(BaseDialogFragment.DISMISSABLE, true);
                                            search.setArguments(b);
                                            search.show(fragment.getActivity().getSupportFragmentManager(), POISearchDialogFragment.TAG);
                                        }
                                    }
                                };
                                if (latLng[0] == null) {
                                    //fragment.startActivityForResult();
                                    //如果无gps，提示用户打开gps
                                    if (!CommonUtil.isGPSEnable(fragment.getActivity())) {//gps未打开
                                        Toast.makeText(fragment.getActivity(), fragment.getString(R.string.please_turn_on_gps), Toast.LENGTH_SHORT).show();
                                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                        fragment.startActivityForResult(myIntent, WebActivity.REQUEST_LOCATION);
                                    } else {
                                        //定位5s，若定位不到，手动签到，若定位到，继续判断距离
                                        ((FBaseActivity) fragment.getActivity()).processPreview("定位中", null, false);
                                        Intent intent = new Intent(ContextManager.context(), LocationService.class);
                                        final ServiceConnection conn = LocationService.connection(null, intent);
                                        ContextManager.context().bindService(intent, conn, Context.BIND_AUTO_CREATE);
                                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                ((FBaseActivity) fragment.getActivity()).processDismiss();
                                                ContextManager.context().unbindService(conn);
                                                latLng[0] = LocationService.getRealTimeLatLngTimeless();
                                                if (latLng[0] == null) {
                                                    //Toast.makeText(fragment.getActivity(), "定位失败，请手动签到，上传照片", Toast.LENGTH_SHORT).show();
                                                    DialogFragment search = new SignFailureChoiceFragment();
                                                    Bundle b = new Bundle();
                                                    if (order != null && order.getTicketid() != null)
                                                        b.putString(fragment.getActivity().getString(R.string.ticketid), order.getTicketid());
                                                    b.putBoolean(BaseDialogFragment.DISMISSABLE, true);
                                                    b.putString(fragment.getActivity().getString(R.string.location_invalid_info), "定位失败, 请尝试拍照到场");
                                                    search.setArguments(b);
                                                    search.show(fragment.getActivity().getSupportFragmentManager(), POISearchDialogFragment.TAG);
                                                } else {
                                                    //Toast.makeText(fragment.getActivity(), "定位成功，可继续签到", Toast.LENGTH_SHORT).show();
                                                    signRunnable.run();
                                                }
                                            }
                                        }, 5000);
                                    }

                                } else if (latLng[0] != null) {
                                    //测算距离, 距离1000
                                    signRunnable.run();
                                }
                            } else if (shortcut.getLink() != null) {
                                Intent intent = new Intent(ContextManager.context(), WebActivity.class);
                                intent.putExtra(FConstants.X5WEBVIEW_INITIAL_URL, String.format(MSConstants.APIConstants.ORDER_ACTIVITI, order.getTicketid(), shortcut.getLink()));
                                intent.putExtra(WebActivity.ORDER, order);
                                DLog.d("order detail", String.format(MSConstants.APIConstants.ORDER_ACTIVITI, order.getTicketid(), shortcut.getLink()));
                                List<Activity> activities = FBaseActivity.getActivites();
                                for (Activity a : activities) {
                                    if (a instanceof MainActivity)
                                        a.startActivityForResult(intent, MSConstants.FragmentType.FRAGMENT_ACTIVORDERS);
                                }
                            }

                        }
                    });
                    DLog.i("icon shortcut", MSConstants.APIConstants.APISERVER_ADDRESS_STATIC_IMAGE + shortcut.getIcon());
                }
                holder.contentTV2.setText("上门地址:" + replaceNull(order.getCaddress()));
                holder.contentTV3.setText("项目名称:" + replaceNull(order.getProject()));
                //holder.layout_grab_order.setBackgroundColor(Color.BLACK);
                //holder.layout_confirm.setBackgroundColor(Color.BLACK);
                //holder.contentRelative.setBackgroundColor(Color.BLACK);
                //holder.layout_back_receive.setBackgroundColor(Color.BLACK);
                //先写一下逻辑吧：若为到场，距离在1000米以内 的工单
                break;
            case MSConstants.FragmentType.FRAGMENT_HISTORYORDERS://历史工单
                if (fragment.getString(R.string.routing_inspection_order).equalsIgnoreCase(replaceNull(order.getTickettype()))) {
                    holder.topTV1.setText("<主动巡检>" + title);
                }
                //第一行
                holder.topTV1.setVisibility(View.VISIBLE);
                holder.topTV3.setVisibility(View.VISIBLE);
                //holder.item_hourTV.setVisibility(View.GONE);
                //holder.item_statusTV.setVisibility(View.GONE);

                //第二行
                holder.topTV2.setVisibility(View.VISIBLE);
                holder.layoutContentTV1.setVisibility(View.VISIBLE);
                holder.layoutContentTV2.setVisibility(View.VISIBLE);
                holder.contentDistanceTV.setVisibility(View.GONE);
                holder.layoutContentTV3.setVisibility(View.VISIBLE);
                holder.contentRelative.setVisibility(View.GONE);
                holder.layoutContentTV5.setVisibility(View.GONE);
                //第三行
                holder.bottomLinear.setVisibility(View.GONE);
                //新加入布局
                holder.layout_worksheet_left.setVisibility(View.GONE);
                holder.layout_back_layout.setVisibility(View.GONE);
                holder.layout_grab_order.setVisibility(View.GONE);
                holder.layout_grab_time.setVisibility(View.GONE);

                //历史工单赋值操作
                String orderLevel_history = replaceNull(order.getRespondLevel());
                showPriority(holder.topTV3, order.getPriority(), order.getRespondLevel());

                holder.status_topTVs.setText(replaceNull(order.getAppstatus()));

                //holder.contentTV3.setText("项目名称:" + replaceNull(order.getProject()));
                holder.contentTV3.setText(replaceNull(order.getProject()));
                //holder.topTV2.setText("工单编号:" + replaceNull(order.getTicketid()));
                holder.topTV2.setText(replaceNull(order.getTicketid()));
                if (order.getcTime() != null)
                    //holder.topTV2.setText("工单编号:" + replaceNull(order.getTicketid()));
                    holder.contentTV1.setText(formater.format(order.getcTime()));
                else
                    //holder.contentTV1.setText("结束时间:未知");
                    holder.contentTV1.setText("未知");
                //holder.contentTV2.setText("上门地址:" + replaceNull(order.getCaddress()));
                holder.contentTV2.setText(replaceNull(order.getCaddress()));
                holder.contentTV5.setText("客户评价:" + replaceNull(order.getEvaluate()));
                holder.ivEvaluation.setVisibility(View.VISIBLE);
                showHistoryEvaluation(fragment, holder.ivEvaluation, replaceNull(order.getEvaluate()), order.getState(), order.getTickettype());
                break;
        }
    }

    private static void showOverTime(Order mOrder, Context mTimeContext, RelativeLayout mOverLayout, TextView timeTv, Date[] twoVals, String key, String defVal, ImageView timeIcon, ImageView notOver, ImageView alreadyOver) {
        //当前时间超过当前阶段对应的SLA预警时间时，
        // 工单显示"即将超时"，SLA时间红色显示；
        // 当前时间超过当前阶段对应的SLA超时时间时，
        // 工单显示“超时”。SLA时间红色显示
        notOver.setVisibility(View.INVISIBLE);
        alreadyOver.setVisibility(View.INVISIBLE);
        mOverLayout.setBackgroundResource(R.drawable.btn_blue_normal_shape);
        if (twoVals != null && twoVals.length == DATE_LEN && key != null) {
            timeTv.setText(key + ":" + formater.format(twoVals[1]));
            //当前时间超过SLA超时时间
            if (twoVals[1] != null && System.currentTimeMillis() >= twoVals[1].getTime()) {
                timeTv.setTextColor(mTimeContext.getResources().getColor(R.color.color_red_over_time));
                timeIcon.setImageResource(R.drawable.icon_red_over_time);
                notOver.setVisibility(View.GONE);
                alreadyOver.setVisibility(View.VISIBLE);
                mOverLayout.setBackgroundResource(R.drawable.btn_red_over_time_shape);
                //notifyAndSendInfo(mTimeContext.getString(R.string.overtime_react), mOrder, mTimeContext);

            } else if (twoVals[0] != null && System.currentTimeMillis() >= twoVals[0].getTime()) {//当前时间超过SLA预警时间
                timeTv.setTextColor(mTimeContext.getResources().getColor(R.color.color_red_over_time));
                timeIcon.setImageResource(R.drawable.icon_red_over_time);
                alreadyOver.setVisibility(View.GONE);
                notOver.setVisibility(View.VISIBLE);
                mOverLayout.setBackgroundResource(R.drawable.btn_red_over_time_shape);
                //如果是【已接单，待预约】状态的工单，1 查询通知数据库，如已有这条数据，不做任何操作，如果没有这条数据，插入，发一个通知
                //notifyAndSendInfo(mTimeContext.getString(R.string.overtime_alarm), mOrder, mTimeContext);
            } else {
                timeTv.setTextColor(mTimeContext.getResources().getColor(R.color.color_gray_over_time));
                timeIcon.setImageResource(R.drawable.icon_orderlistitem_giveorder_time);
                alreadyOver.setVisibility(View.INVISIBLE);
                notOver.setVisibility(View.INVISIBLE);
                mOverLayout.setBackgroundResource(R.drawable.btn_blue_normal_shape);
            }
        } else {
            timeTv.setText(defVal);
        }
    }

    private static void notifyAndSendInfo(final String title, final Order mOrder, final Context mTimeContext) {
        //如果是【已接单，待预约】状态的工单，1 查询通知数据库，如已有这条数据，不做任何操作，如果没有这条数据，插入，发一个通知
        if (mTimeContext.getString(R.string.receiveorder).equals(mOrder.getDescription()[0]) && mTimeContext.getString(R.string.appoint).equals(mOrder.getDescription()[1])) {
            final NotificationDao notificationDao = MSApplication.getDaoSession().getNotificationDao();
            List<Notification> notifications = notificationDao.queryBuilder().where(NotificationDao.Properties.Title.eq(mOrder.getTicketid()), NotificationDao.Properties.Desc.eq(title)).build().list();
            if (notifications.size() == MSConstants.OtherConstance.NOTIFICATION_EMPTY) {
                //存入数据库
                String content = title + "：\n编号为: " + mOrder.getTicketid() + "工单在服务实施环节，需要您及时处理。";
                final Notification notification = new Notification();
                notification.setContent(content);
                notification.setTitle(mOrder.getTicketid());
                notification.setDesc(title);
                notification.setType(NotificationAdapter.MESSAGETYPE.SLA_NOTIFY_ACTIVE_ORDER);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        notificationDao.insert(notification);
                        SendNotification.sendNotification(R.drawable.ic_launcher, title, "编号为:" + mOrder.getTicketid() + "工单在服务实施环节，需要您及时处理。", mTimeContext, true, R.string.auto_sign_pls, PendingIntent.FLAG_UPDATE_CURRENT, MainActivity.OPEN_ORDER_SIGN);
                    }
                }).start();
            }

            //NotificationDao notificationDao = MSApplication.getDaoSession().getNotificationDao();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<Notification> notificationSize = notificationDao.queryBuilder().list();
                    if (notificationSize != null && notificationSize.size() > MSConstants.OtherConstance.NOTIFICATION_FULL) {
                        notificationDao.deleteAll();
                    }
                }
            }).start();
        }
    }

    private static void showHistoryEvaluation(Fragment mFragment, ImageView imageView, String evaluation, int state, String routing) {
        if (mFragment.getString(R.string.routing_inspection_order).equalsIgnoreCase(replaceNull(routing))) {
            imageView.setImageResource(R.drawable.routing_inspection);
        } else if (7 == state) {
            imageView.setImageResource(R.drawable.close_order_qucikly);
        } else {
            if (OrderLevel.EVALUATION_BAD.getLevel().equals(evaluation)) {
                imageView.setImageResource(R.drawable.evaluation_bad);
            } else if (OrderLevel.EVALUATION_GOOD.getLevel().equals(evaluation)) {
                imageView.setImageResource(R.drawable.evaluation_good);
            } else if (OrderLevel.EVALUATION_NICE.getLevel().equals(evaluation)) {
                imageView.setImageResource(R.drawable.evaluation_nice);
            } else if (OrderLevel.EVALUATION_WONDERFUL.getLevel().equals(evaluation)) {
                imageView.setImageResource(R.drawable.evaluation_wonderful);
            }
        }
    }

    public static void gotoAppointPage(Fragment fragment, Order order, String activiti, int type) {
        // 打开新预约界面
        Intent intent = new Intent(ContextManager.context(), WebActivity.class);
        intent.putExtra(WebActivity.ORDER, order);
        intent.putExtra(FConstants.X5WEBVIEW_INITIAL_URL, String.format(MSConstants.APIConstants.ORDER_ACTIVITI, order.getTicketid(), activiti));
        intent.putExtra(FBaseActivity.PRE_RESULT, Activity.RESULT_OK);
        DLog.d("order detail", String.format(MSConstants.APIConstants.ORDER_ACTIVITI, order.getTicketid(), activiti));
        //切换到活动工单
        List<Activity> list = FBaseActivity.getActivites();
        for (int i = list.size() - 1; i >= 0; i--) {
            if (fragment.getActivity() != list.get(i) && !(list.get(i) instanceof MainActivity)) {
                ((FBaseActivity) list.get(i)).defaultFinish();
            } else {
                if (list.get(i) instanceof MainActivity) {
                    ((MainActivity) list.get(i)).onPageSelected(MainActivity.PAGE_ACTIVE_ORDER, false);
                    list.get(i).startActivityForResult(intent, type);
                    break;
                }
            }
        }
        fragment.getActivity().finish();
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    private static void setImgViewParams(View contentRelative, double v) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        contentRelative.measure(w, h);
        int width = contentRelative.getMeasuredWidth();
        int height = contentRelative.getMeasuredHeight();
        ViewGroup.LayoutParams params = contentRelative.getLayoutParams();
        params.width = (int) (width * v);
        params.height = (int) (height * v);
        contentRelative.setLayoutParams(params);
    }

    @Override
    public int getItemCount() {
        return orderList == null || orderList.size() == 0 ? 0 : orderList.size();
    }

    public void setListData(List<Order> listData) {
        this.orderList.clear();
        orderShadowList = null;
        if (listData == null) return;
        this.orderList.addAll(listData);
    }

    public void addListData(List<Order> listData) {
        this.orderList.addAll(listData);
        orderShadowList = null;
    }

    public ArrayList<Order> getOrderList() {
        return orderList;
    }

    public void filterList(String text) {
        if (orderShadowList == null) {
            orderShadowList = new ArrayList<>();
            orderShadowList.addAll(orderList);
        }
        orderList.clear();
        orderList.addAll(orderShadowList);
        if (text == null || text.trim().isEmpty()) {
            orderShadowList = null;
            return;
        }
        Iterator<Order> iterator = orderShadowList.iterator();
        while (iterator.hasNext()) {
            Order item = iterator.next();
            DLog.w("search", item.toString() + " contain " + item.toString().contains(text));
            if (!item.toString().contains(text)) {
                DLog.w("search", "remove" + item.getTicketid());
                orderList.remove(item);
            }
        }
        DLog.w("search", "size" + orderList.size());
        DLog.w("search", "size shadow" + orderShadowList.size());

    }


    class OrderViewHolder extends com.lenovo.mso2o.ui.adapter.OrderViewHolder implements View.OnClickListener {

        public OrderViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition() - 1;
            if (listener != null && position != -1) {
                Order order = orderList.get(position);
                listener.onOrderSelected(order, v.getContext());
            }
        }
    }

    public interface OnOrderSelectedListener {
        void onOrderSelected(Order order, Context context);

        void onConfirmClick();
    }

    private static String replaceNull(String pattern) {
        return pattern == null ? "" : pattern;
    }

    @Override
    public void finalize() {
        _subscription = null;
    }
}

